import {
  applyDecorators,
  UnsupportedMediaTypeException,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';
//filed代表的是上传名称,默认是file,options代表的是上传选项
export function Upload(filed = 'file', options: MulterOptions = {}) {
  return applyDecorators(UseInterceptors(FileInterceptor(filed, options)));
}

export function FileFilter(type: string) {
  return (
    req: any,
    file: any,
    callback: (error: Error | null, acceptFile: boolean) => void,
  ) => {
    if (!file.mimetype.includes(type)) {
      callback(new UnsupportedMediaTypeException('文件类型错误'), false);
    } else {
      callback(null, true);
    }
  };
}

export function ImageUpload(field = 'file') {
  return Upload(field, {
    limits: { fieldSize: Math.pow(1024, 2) * 2 },
    fileFilter: FileFilter('image'),
  });
}
